package com.yqya.springboot.websocket.chat.controller;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 聊天
 *
 * @author Kevin
 * @date 2019-07-07
 */
@RestController
public class ChatController {

    /**
     * 登录界面
     */
    @GetMapping("/")
    public ModelAndView login() {
        return new ModelAndView("/login");
    }

    /**
     * 聊天界面
     */
    @GetMapping("/index")
    public ModelAndView index(String username, String password, HttpServletRequest request) throws UnknownHostException {
        if (StringUtils.isBlank(username)) {
            username = "匿名用户";
        }

        ModelAndView mav = new ModelAndView("/chat");
        mav.addObject("username", username);

        StringBuilder webSocketUrl = new StringBuilder("ws://");
        webSocketUrl.append(InetAddress.getLocalHost().getHostAddress());
        webSocketUrl.append(":");
        webSocketUrl.append(request.getServerPort());
        webSocketUrl.append(":");
        webSocketUrl.append(request.getContextPath());
        webSocketUrl.append("/chat");
        mav.addObject("webSocketUrl", webSocketUrl.toString());
        return mav;
    }


}
